<template>
  <div class="page-container">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title-bold">登机口管理</span>
          <div class="search-bar">
            <el-input
              v-model="searchQuery"
              placeholder="请输入登机口编号或航班号"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="handleSearchClear"
              @keyup.enter="handleSearch"
            />
            <el-button type="primary" @click="handleSearch">
              查询
            </el-button>
            <el-button @click="resetAll">
              重置
            </el-button>
          </div>
        </div>
      </template>
      <el-table
        :data="gateList"
        border
        style="width: 100%"
        class="data-table"
        v-loading="loading"
      >
        <el-table-column prop="FLID" label="航班号" min-width="120" align="center" />
        <el-table-column prop="GTNO" label="登机口序号" min-width="120" align="center" />
        <el-table-column prop="CODE" label="登机口编号" min-width="120" align="center" />
        <el-table-column prop="BTSC" label="所属楼号" min-width="120" align="center" />
        <el-table-column prop="RSTR" label="开始时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.RSTR) }}
          </template>
        </el-table-column>
        <el-table-column prop="REND" label="结束时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.REND) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)" effect="light">
              {{ getStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right" v-if="$store.getters.currentRole === 'admin'">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                @click="handleEdit(row)"
                class="action-btn"
                type="primary"
                plain
              >
                <span>编辑</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 15, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="40%"
      class="custom-dialog"
      @close="resetForm"
    >
      <el-form
        :model="gateForm"
        :rules="rules"
        ref="gateFormRef"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="航班号" prop="FLID">
          <el-input v-model="gateForm.FLID" placeholder="请输入航班号"></el-input>
        </el-form-item>
        <el-form-item label="登机口序号" prop="GTNO">
          <el-input v-model="gateForm.GTNO" placeholder="请输入登机口序号"></el-input>
        </el-form-item>
        <el-form-item label="登机口编号" prop="CODE">
          <el-input v-model="gateForm.CODE" placeholder="请输入登机口编号"></el-input>
        </el-form-item>
        <el-form-item label="所属楼号" prop="BTSC">
          <el-input v-model="gateForm.BTSC" placeholder="请输入所属楼号"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="RSTR">
          <el-date-picker
            v-model="gateForm.RSTR"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="REND">
          <el-date-picker
            v-model="gateForm.REND"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="submitForm">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { BoardingGateApi } from '@/api/flight'
import axios from 'axios'

// 状态管理
const loading = ref(false)
const gateList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const isSearching = ref(false)

// 表单数据
const gateForm = ref({
  FLID: '',
  GTNO: '',
  CODE: '',
  BTSC: '',
  RSTR: '',
  REND: ''
})

// 表单验证规则
const rules = {
  FLID: [
    { required: true, message: '请输入航班号', trigger: 'blur' }
  ],
  GTNO: [
    { required: true, message: '请输入登机口序号', trigger: 'blur' }
  ],
  CODE: [
    { required: true, message: '请输入登机口编号', trigger: 'blur' }
  ],
  BTSC: [
    { required: true, message: '请输入所属楼号', trigger: 'blur' }
  ],
  RSTR: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  REND: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 对话框相关
const dialogVisible = ref(false)
const isAdd = ref(true)
const dialogTitle = computed(() => isAdd.value ? '添加登机口' : '编辑登机口')
const gateFormRef = ref(null)

// 时间解析与格式化
const parseDbTime = (dbTime) => {
  if (!dbTime || dbTime.length !== 14) return null

  try {
    const year = dbTime.substring(0, 4)
    const month = dbTime.substring(4, 6)
    const day = dbTime.substring(6, 8)
    const hour = dbTime.substring(8, 10)
    const minute = dbTime.substring(10, 12)
    const second = dbTime.substring(12, 14)

    return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`)
  } catch (e) {
    console.error('时间解析错误:', e)
    return null
  }
}

const formatDateTime = (dbTime) => {
  const date = parseDbTime(dbTime)
  return date ? date.toLocaleString('zh-CN') : '-'
}

// 状态处理
const getStatusText = (row) => {
  let status = '启用中'

  try {
    const now = new Date()
    const start = parseDbTime(row.RSTR)
    const end = parseDbTime(row.REND)

    if (start && now < start) status = '未开始'
    if (end && now > end) status = '已结束'
    if (start && end && now >= start && now <= end) status = '使用中'
  } catch (e) {
    console.error('状态判断错误:', e)
    status = '未知'
  }

  return status
}

const getStatusType = (row) => {
  const status = getStatusText(row)
  switch (status) {
    case '未开始': return 'info'
    case '使用中': return 'success'
    case '已结束': return 'warning'
    default: return 'danger'
  }
}

// 搜索相关
const handleSearch = async () => {
  if (searchQuery.value.trim()) {
    isSearching.value = true
    currentPage.value = 1
    await fetchBoardingGates()
  } else {
    resetAll()
  }
}

const handleSearchClear = () => {
  if (isSearching.value) {
    resetAll()
  }
}

const resetAll = async () => {
  searchQuery.value = ''
  isSearching.value = false
  currentPage.value = 1
  pageSize.value = 10
  await fetchBoardingGates()
}

// 数据获取
const fetchBoardingGates = async () => {
  try {
    loading.value = true
    let response

    if (isSearching.value && searchQuery.value) {
      response = await BoardingGateApi.getBoardingGatesByCode(searchQuery.value, currentPage.value, pageSize.value)

      if (!response.data || response.data.length === 0) {
        response = await BoardingGateApi.getBoardingGatesByFlightId(searchQuery.value, currentPage.value, pageSize.value)
      }
    } else {
      response = await BoardingGateApi.getAllBoardingGates(currentPage.value, pageSize.value)
    }

    if (response.data) {
      gateList.value = response.data.data || response.data || []
      total.value = response.totalRecords || response.total || 0
    }
  } catch (error) {
    ElMessage.error('获取登机口数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchBoardingGates()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchBoardingGates()
}

// 编辑操作
const handleEdit = (row) => {
  isAdd.value = false
  gateForm.value = {
    ...row,
    FLID: row.FLID,
    GTNO: row.GTNO,
    CODE: row.CODE,
    BTSC: row.BTSC,
    RSTR: parseDbTime(row.RSTR),
    REND: parseDbTime(row.REND)
  }
  dialogVisible.value = true
}

// 表单重置
const resetForm = () => {
  gateFormRef.value?.resetFields()
  gateForm.value = {
    FLID: '',
    GTNO: '',
    CODE: '',
    BTSC: '',
    RSTR: '',
    REND: ''
  }
}

// 表单提交
const submitForm = async () => {
  try {
    await gateFormRef.value.validate()

    const formatToDbTime = (date) => {
      if (!date) return ''
      const d = date instanceof Date ? date : new Date(date)
      return [
        d.getFullYear(),
        (d.getMonth() + 1).toString().padStart(2, '0'),
        d.getDate().toString().padStart(2, '0'),
        d.getHours().toString().padStart(2, '0'),
        d.getMinutes().toString().padStart(2, '0'),
        d.getSeconds().toString().padStart(2, '0')
      ].join('')
    }

    const formData = {
      dfltFlid: gateForm.value.FLID,
      gtno: gateForm.value.GTNO,
      code: gateForm.value.CODE,
      btsc: gateForm.value.BTSC,
      rstr: formatToDbTime(gateForm.value.RSTR),
      rend: formatToDbTime(gateForm.value.REND)
    }
    // 添加 baseURL 以确保请求路径正确
    const apiClient = axios.create({
      baseURL: 'http://localhost:8081', // 根据你的实际后端地址修改
      timeout: 10000
    })
    // 发送请求（注意这里使用相对路径，因为baseURL已经设置）
    await apiClient.put('http://localhost:8081/flightUpdate/updateGtlGateByDfltFlid', formData)

    // 如果请求成功（没有抛出异常），则认为更新成功
    ElMessage.success('更新成功')
    dialogVisible.value = false
    fetchBoardingGates()
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
    console.error('更新登机口失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchBoardingGates()
})
</script>

<style scoped>

.title-bold {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.main-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-container {
  display: flex;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-title h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-icon {
  font-size: 20px;
  color: var(--el-color-primary);
}

.search-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  gap: 10px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 6px;
}

.data-table {
  margin-top: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.data-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.data-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

.custom-dialog {
  border-radius: 8px;
}

.dialog-btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px;
}
</style>
